﻿using Microsoft.AspNetCore.Mvc;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace WallpaperApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BaseController : ControllerBase
    {
        protected string UserId => GetUserId();
        protected string Account => GetAccount();
        protected string AdminId => GetAdminId();

        /// <summary>
        /// 获取用户ID（只从用户Token中获取）
        /// </summary>
        protected string GetUserId()
        {
            // 先检查是否是用户
            var userType = HttpContext?.User?.FindFirst("type")?.Value;
            Console.WriteLine($"User type from token: '{userType}'"); // 调试
            if (userType != "user")
            {
                throw new UnauthorizedAccessException("当前用户不是普通用户");
            }
            // 再获取ID
            var userId = HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value
                      ?? HttpContext?.User?.FindFirst("sub")?.Value;
            if (string.IsNullOrEmpty(userId))
            {
                throw new UnauthorizedAccessException("用户ID不存在");
            }
            return userId;
        }

        protected string GetAccount()
        {
            var account = HttpContext?.User?.FindAll("account").ToString();
            if (string.IsNullOrEmpty(account))
            {
                throw new UnauthorizedAccessException("用户未认证或Token无效");
            }
            return account;
        }

        /// <summary>
        /// 获取管理员ID（只从管理员Token中获取）
        /// </summary>
        protected string GetAdminId()
        {
            // 先检查是否是管理员
            var userType = HttpContext?.User?.FindFirst("type")?.Value;
            if (userType != "admin")
            {
                throw new UnauthorizedAccessException("当前用户不是管理员");
            }

            // 再获取ID
            var adminId = HttpContext?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value
                       ?? HttpContext?.User?.FindFirst("sub")?.Value;
            if (string.IsNullOrEmpty(adminId))
            {
                throw new UnauthorizedAccessException("管理员ID不存在");
            }
            return adminId;
        }
    }
}
